package com.ruoyi.common.utils;

//import com.google.common.collect.Lists;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.springframework.util.CollectionUtils;

import java.nio.charset.Charset;
import java.text.DateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

public final class SqlUtils extends com.baomidou.mybatisplus.core.toolkit.sql.SqlUtils {
    /**
     * 只能项目内部使用, 传入id 等非 sql注入 的参数
     * @param strs [str1,str2,str3,...]
     * @param wrap  是否用单引号引起每个值
     * @return 'str1','str2','str3',...
     */
    public static <T>String in(List<T> strs, boolean wrap){
        return String.join(",", strs.stream().filter(Objects::nonNull).map(x->{
            String s=x.toString();
            if(wrap) return wrap(s);
            return s;
        }).distinct().collect(Collectors.toList()));
    }

    /**
     * 只能项目内部使用, 传入id 等非 sql注入 的参数
     * @param str str
     * @return 'str'
     */
    public static String wrap(String str) {
        if(str==null) return "NULL";
        return "'"+str.replace("'", "''").replace("\\","\\\\")+"'";
    }

    private static String escape(String v){
        return v == null ? null : StringUtils.replace(v, "'", "''");
    }


    private static String SPEC_CHARS_FOR_SEMICOLON="\2\3";
    private static String SPEC_CHARS_FOR_QUESTION_MARK="\5\6";

    public static String STR(Object obj){ return STR(obj,null); }
    public static String STR(Object obj,String defStr){
        if(obj==null) return defStr;
        if(obj instanceof String) return (String)obj;
        String str=obj.toString();
        if(StringUtils.isBlank(str)) return defStr;
        return str;
    }
    public static String escapeSql(String str) {
        if (str == null) {
            return null;
        }
        return StringUtils.replace(str, "'", "''");
    }
    public static String quotSTR(String str){
        return "'"+ SqlUtils.escapeSql(str)+"'";
    }
    public static <T>String in(Collection<T> fieldValues) throws Exception{
        String result="";
        for(Object obj: fieldValues){
            String v=STR(obj);
            if(v!=null) result+=","+quotSTR(v);
        }
        if("".equals(result)) throw new Exception("SQL IN 参数至少需要包含一个值");
        return result.substring(1);
    }


    private static List<String> splitToSingleSqls(String originalSql){
        String[] preSqls=originalSql.split(";");
//        List<String> doneSqls= Lists.newArrayList();
        List<String> doneSqls = new ArrayList<>();
        for(String preSql: preSqls){
            String finalSql=preSql.trim();
            if(finalSql.startsWith("begin") || finalSql.startsWith("BEGIN")) finalSql=finalSql.substring(5).trim();
            if("end".equals(finalSql) || "END".equals(finalSql)) continue; //忽略
            String sql=finalSql.replace(SPEC_CHARS_FOR_QUESTION_MARK, "?").replace(SPEC_CHARS_FOR_SEMICOLON, ";");
            doneSqls.add(sql);
            System.err.println(sql);
        }
        return doneSqls;
    }
    public static List<String> getMappedSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();  // 获取参数
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");  // sql语句中多个空格都用一个空格代替
        if (!CollectionUtils.isEmpty(parameterMappings) && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); // 获取类型处理器注册器，类型处理器的功能是进行java类型和数据库类型的转换<br>　　　　　　　// 如果根据parameterObject.getClass(）可以找到对应的类型，则替换
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(parameterObject)));
            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);// MetaObject主要是封装了originalObject对象，提供了get和set的方法用于获取和设置originalObject的属性值,主要支持对JavaBean、Collection、Map三种类型对象的操作
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);  // 该分支是动态sql
                        sql = sql.replaceFirst("\\?", Matcher.quoteReplacement(getParameterValue(obj)));
                    } else {
                        sql = sql.replaceFirst("\\?", "NULL");
                    }//打印出缺失，提醒该参数缺失并防止错位
                }
            }
            //			if (hasLobData(configuration, boundSql)) { // 日前只支持一个字段为 blob 的情况 (SP_APPLY_INFO), 并且第一个字段必须为 ID_
            //				// 对超长的 sql 拆分成若干条 sql
            //			}
        }
        return splitToSingleSqls(sql);
    }
    public static String getParameterValue(Object obj) {
        if (obj == null) return "NULL";
        String value;
        if (obj instanceof String) {
            value = SqlUtils.quotSTR(obj.toString());
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            Date pDate=(Date)obj;
            value = "TO_DATE('" + formatter.format(pDate) + "','yyyy-mm-dd hh24:mi:ss')";
        } else if (obj instanceof byte[]) {
            String utf8Str = new String((byte[]) obj, Charset.forName("UTF-8"));
            List<String> strs = SqlUtils.splitStrToFixedLen(utf8Str, 200);
            value = "";
            for (String str : strs) value += "||UTL_RAW.CAST_TO_RAW(" + SqlUtils.quotSTR(str) + ")";
            if (value.length() > 0) value = value.substring(2);
        } else {
            value = obj.toString();
        }
        if (!StringUtils.isBlank(value)) {
            value = value.replace(";", SPEC_CHARS_FOR_SEMICOLON).replace("?", SPEC_CHARS_FOR_QUESTION_MARK);
        }
        return value;
    }

    public static List<String> splitStrToFixedLen(String inputString, int fixedLen) {
        int len=inputString.length();
        if(len<=fixedLen) return new ArrayList<String>(Collections.singleton(inputString));
//        if(len<=fixedLen) return  Lists.newArrayList(inputString);

//        List<String> list=Lists.newArrayList();

        List<String> list = new ArrayList<>();
        int start=0, end=0;
        while(end<len){
            end= start+fixedLen;
            if(end>len) end=len;
            list.add(inputString.substring(start, end));
            start=end;
        }
        return list;
    }
}
